package com.commun;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import maps.test.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.location.Address;
import android.location.Geocoder;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.activity.MyMapActivity;
import com.calque.CalqueSitesClientTempMosqueAjouter;
import com.commun.Utils.CalqueEnum;
import com.data.DataBaseQuery;
import com.google.android.maps.GeoPoint;
import com.object.Mosque;
import com.object.OverlayItemCustom;

public class AjouterMosque {

	public static boolean isActivate;
	public static boolean isTagButtonActivate;
	public static GeoPoint tapMosqueGeoPoint;
	public static boolean isTaptagOnMapDetected;

	public static void EditAjoutMosqueEnabling() {
		if (!isActivate) {
			isActivate = true;
			TabHost tabHost = (TabHost) ((Activity) MyMapActivity.getmContext())
					.findViewById(R.id.TabHostMenu);
			tabHost.setCurrentTab(1);
			RelativeLayout ajoutMosqueTagButtom = (RelativeLayout) ((Activity) MyMapActivity
					.getmContext())
					.findViewById(R.id.ajouter_mosque_parent_layout);
			ajoutMosqueTagButtom.setVisibility(View.VISIBLE);

		} else {
			Toast.makeText(MyMapActivity.getmContext(), "Mode d�jas activ�",
					Toast.LENGTH_SHORT).show();
		}

	}

	public static void ShowDialogSaisiInfo() {// insertion ou modif

		CalqueSitesClientTempMosqueAjouter.getInstance().AddCalque(
				AjouterMosque.tapMosqueGeoPoint);

		final Dialog dialog = new Dialog(MyMapActivity.getmContext());
		dialog
				.setContentView(R.layout.ajouter_mosque_layout_insertion_information);
		dialog.setTitle("Saisir les informations");
		dialog.setCancelable(true);
		final Spinner spinnerType = (Spinner) dialog
				.findViewById(R.id.$info_type_mosque);
		ArrayAdapter<CharSequence> adapterTypeMosqué = ArrayAdapter
				.createFromResource(MyMapActivity.getmContext(),
						R.array.type_mosque,
						android.R.layout.simple_spinner_dropdown_item);
		spinnerType.setAdapter(adapterTypeMosqué);
		TextView text = (TextView) dialog.findViewById(R.id.$info_addresse);
		final String addresse = GetAddresseFromGeoPoint(tapMosqueGeoPoint);
		text.setText(addresse);
		LinearLayout layout = (LinearLayout) dialog
				.findViewById(R.id.layout_validation_buttons);
		Button annuler = (Button) layout
				.findViewById(R.id.ButtonAnnulationSaisiInfo);
		annuler.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				CalqueSitesClientTempMosqueAjouter.getInstance()
						.removeLastItem();
				dialog.cancel();
			}

		});
		Button valider = (Button) layout
				.findViewById(R.id.ButtonDeValidationSaisiInfo);
		valider.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				EditText nom = (EditText) dialog.findViewById(R.id.$info_nom);
				if (nom.getText().toString().length() > 0) {
					Mosque mosque = new Mosque(nom.getText().toString().trim(),
							spinnerType.getSelectedItem().toString(), addresse);
					CalqueSitesClientTempMosqueAjouter.getInstance().AddCalque(
							AjouterMosque.tapMosqueGeoPoint, mosque);

					nom.setText("");
					dialog.dismiss();

				}

			}

		});

		dialog.show();
	}

	public static void ShowDialogModificationInfo(int ID) {
		OverlayItemCustom item = CalqueSitesClientTempMosqueAjouter
				.getInstance().GetItem(ID);
		CalqueSitesClientTempMosqueAjouter.getInstance().AddCalque(
				AjouterMosque.tapMosqueGeoPoint);

		final Dialog dialog = new Dialog(MyMapActivity.getmContext());
		dialog
				.setContentView(R.layout.ajouter_mosque_layout_insertion_information);
		dialog.setTitle("Saisir les informations");
		dialog.setCancelable(true);
		final Spinner spinnerType = (Spinner) dialog
				.findViewById(R.id.$info_type_mosque);
		ArrayAdapter<CharSequence> adapterTypeMosqué = ArrayAdapter
				.createFromResource(MyMapActivity.getmContext(),
						R.array.type_mosque,
						android.R.layout.simple_spinner_dropdown_item);
		spinnerType.setAdapter(adapterTypeMosqué);
		if (item.getMosquai().getInfo().equals("Jama"))
			spinnerType.setSelection(0);
		else
			spinnerType.setSelection(1);

		TextView text = (TextView) dialog.findViewById(R.id.$info_addresse);
		final EditText nom = (EditText) dialog.findViewById(R.id.$info_nom);
		nom.setText(item.getMosquai().getNom());
		final String addresse = item.getMosquai().getAddresse();
		text.setText(addresse);
		LinearLayout layout = (LinearLayout) dialog
				.findViewById(R.id.layout_validation_buttons);
		Button annuler = (Button) layout
				.findViewById(R.id.ButtonAnnulationSaisiInfo);
		annuler.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {

				dialog.cancel();
			}

		});
		Button valider = (Button) layout
				.findViewById(R.id.ButtonDeValidationSaisiInfo);
		valider.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (nom.getText().toString().length() > 0) {
					CalqueSitesClientTempMosqueAjouter.getInstance().remove(
							CalqueSitesClientTempMosqueAjouter.getInstance()
									.GetIdLastOne());
					Mosque mosque = new Mosque(nom.getText().toString().trim(),
							spinnerType.getSelectedItem().toString(), addresse);
					CalqueSitesClientTempMosqueAjouter.getInstance().AddCalque(
							AjouterMosque.tapMosqueGeoPoint, mosque);

					nom.setText("");
					spinnerType.setSelection(0);
					dialog.dismiss();

				}

			}

		});

		dialog.show();
	}

	private static String GetAddresseFromGeoPoint(GeoPoint geoPoint) {

		Geocoder geoCoder = new Geocoder(MyMapActivity.getmContext(), Locale
				.getDefault());
		String add = " ";
		try {
			List<Address> addresses = geoCoder.getFromLocation(geoPoint
					.getLatitudeE6() / 1E6, geoPoint.getLongitudeE6() / 1E6, 1);

			if (addresses.size() > 0) {
				for (int i = 0; i < addresses.get(0).getMaxAddressLineIndex(); i++) {
					add += addresses.get(0).getAddressLine(i);
					if (i == addresses.get(0).getMaxAddressLineIndex() - 1)
						add += ".";
					else
						add += ", ";
				}
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
		return add;
	}

	public static void SetTagIconToDK_Grey() {
		MyMapActivity.ajouterMosqueeTagButton
				.setBackgroundResource(R.drawable.dk_grey_square);
	}

	public static void MyCustomisedTempItemToast(final Context context,
			final String text, final int ID) {

		RelativeLayout relativeLayout = Utils.GetItem_update_layout(context);

		TextView texts = (TextView) relativeLayout
				.findViewById(R.id.item_temp_text);
		texts.setText("   " + text + "  ");
		LinearLayout fakeLayout = (LinearLayout) relativeLayout
				.findViewById(R.id.fake_right);
		ImageButton modifButton = (ImageButton) fakeLayout
				.findViewById(R.id.item_modif_button);
		modifButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				ShowDialogModificationInfo(ID);
			}
		});
		ImageButton deleteButton = (ImageButton) fakeLayout
				.findViewById(R.id.item_delete_button);
		deleteButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				ShowDialogeAlert(context, ID);

			}
		});
		Handler mHandler = new Handler();
		Runnable mUpdateTimeTask = new Runnable() {
			public void run() {
				Utils.GetItem_update_layout(context)
						.setVisibility(View.VISIBLE);
				Utils.calqueEnum = CalqueEnum.TEMP_ITEMS;

				Utils.TOAST_TEXT_LAUNCHED = true;

			}
		};
		mHandler.removeCallbacks(mUpdateTimeTask);

		mHandler.postDelayed(mUpdateTimeTask, Utils.TIME_DELAYING);

	}

	private static void removeTempCalque(Context context, int ID) {
		CalqueSitesClientTempMosqueAjouter.getInstance().remove(ID);
		Utils.DisparitonLayoutTempItemTaost(context);

	}

	private static void ShowDialogeAlert(final Context context, final int ID) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setMessage("Supprimer la Mosqu�e?").setCancelable(false)
				.setPositiveButton("Oui",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								removeTempCalque(context, ID);
							}
						}).setNegativeButton("Non",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});
		AlertDialog alert = builder.create();
		alert.show();
	}

	private static void ShowDialogeTerminerAjoutMosque(final Context context) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		String title = CalqueSitesClientTempMosqueAjouter.getInstance()
				.getItems().isEmpty() ? "Terminer l'ajout?"
				: "Valider les ajouts?";
		builder.setMessage(title).setCancelable(false).setPositiveButton("Oui",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						DataBaseQuery.StateOfTheRequest state = new DataBaseQuery()
								.InsertTempItems();

						if (state == DataBaseQuery.StateOfTheRequest.FAIL) {

							Toast
									.makeText(
											MyMapActivity.getmContext(),
											"Une erreure est survenus lors de l'envois des donn�es",
											Toast.LENGTH_LONG).show();
							Toast
									.makeText(
											MyMapActivity.getmContext(),
											"Veuillez v�rifier la connectivit� de votre appareil au r�seaux internet",
											Toast.LENGTH_LONG).show();

						} else {
							if (state == DataBaseQuery.StateOfTheRequest.DONE)
								Toast
										.makeText(
												MyMapActivity.getmContext(),
												"Vos requ�tes seront trait�es dans le plus proche d�lais, merci.",
												Toast.LENGTH_LONG).show();
							RelativeLayout ajoutMosqueTagButtom = (RelativeLayout) ((Activity) MyMapActivity
									.getmContext())
									.findViewById(R.id.ajouter_mosque_parent_layout);
							ajoutMosqueTagButtom.setVisibility(View.INVISIBLE);
							AjouterMosque.isTagButtonActivate = false;
							CalqueSitesClientTempMosqueAjouter.getInstance()
									.Renitialise();
							AjouterMosque.isActivate = false;
						}

					}
				}).setNegativeButton("Non",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
		AlertDialog alert = builder.create();
		alert.show();
	}

	public static void TeminerAjoutMosque(Context context) {

		ShowDialogeTerminerAjoutMosque(context);
	}

}
